import json
import requests

zabbix_url = "http://192.168.140.10/zabbix/api_jsonrpc.php"
zabbix_user = "Admin"
zabbix_password = "zabbix"

# 登录zabbix，获取令牌
def zabbix_login():
    data = {
           "jsonrpc": "2.0",
           "method": "user.login",
           "params": {
               "user": zabbix_user,
               "password": zabbix_password
           },
           "id": 1,
    }
    head = { "Content-Type":"application/json" }

    res = requests.post(url=zabbix_url, data=json.dumps(data), headers=head)
    token = json.loads(res.text).get("result")
    return token

# 获取被监控机的ID、接口ID
def get_hostid_interfaceid():
    token = zabbix_login()
    data = {
           "jsonrpc": "2.0",
           "method": "host.get",
           "params": {
               "output": [
                   "hostid",
                   "host"
               ],
               "selectInterfaces": [
                   "interfaceid",
                   "ip"
               ]
           },
           "id": 2,
           "auth": token
    }
    head = { "Content-Type":"application/json" }

    res = requests.post(url=zabbix_url, data=json.dumps(data), headers=head)
    hostid = json.loads(res.text).get("result")[1].get("hostid")
    interfaceid =  json.loads(res.text).get("result")[1].get("interfaces")[0].get("interfaceid")
    return hostid, interfaceid

# 添加监控项
def add_item(disk):
    token = zabbix_login()
    hostid, interfaceid = get_hostid_interfaceid()

    data = {
           "jsonrpc": "2.0",
           "method": "item.create",
           "params": {
               "name": "磁盘【%s】的剩余空间" % disk,
               "key_": "vfs.fs.size[%s,free]" % disk,
               "hostid": hostid,
               "type": 0,
               "value_type": 3,
               "interfaceid": interfaceid,
               "delay": 30
           },
           "auth": token,
           "id": 3
    }
    head = { "Content-Type":"application/json" }

    res = requests.post(url=zabbix_url, data=json.dumps(data), headers=head)
    if "error" in res.text:
        print("磁盘【%s】剩余空间监控失败" % disk)
    else:
        print("磁盘【%s】剩余空间监控成功" % disk)



if __name__ == '__main__':
    add_item(disk="/etc")





